package testconfig

import (
	"bytes"
	"context"
	"encoding/json"
	"net/http"

	"yunzhan/alert-server/internal/svc"
	"yunzhan/alert-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type TestSMSLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewTestSMSLogic 短信测试
func NewTestSMSLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TestSMSLogic {
	return &TestSMSLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *TestSMSLogic) TestSMS(req *types.TestSMSRequest) (*types.TestResponse, error) {
	// 检查是否提供了短信配置
	if len(req.Config) == 0 {
		return &types.TestResponse{
			Success: 500,
			Message: "未提供短信配置",
		}, nil
	}

	config := req.Config[0]

	// 准备发送短信的 payload
	payload := map[string]interface{}{
		"api_key":    config.ApiKey,
		"api_secret": config.ApiSecret,
		"to":         config.Recipient,
		"text":       config.Message,
	}
	payloadBytes, err := json.Marshal(payload)
	if err != nil {
		return &types.TestResponse{
			Success: 500,
			Message: "json序列化失败",
		}, err
	}

	// 发送HTTP请求到短信服务提供商
	url := "https://sms-provider.example.com/send" // 请替换为实际的短信服务提供商的API地址
	response, err := http.Post(url, "application/json", bytes.NewBuffer(payloadBytes))
	if err != nil {
		return &types.TestResponse{
			Success: 500,
			Message: "发送请求到短信服务提供商失败",
		}, err
	}
	defer response.Body.Close()

	// 检查响应状态
	if response.StatusCode != http.StatusOK {
		return &types.TestResponse{
			Success: 500,
			Message: "短信服务提供商响应非200状态",
		}, nil
	}

	return &types.TestResponse{
		Success: 200,
		Message: "短信发送成功",
	}, nil
}
